import { useUserStore } from '@/store'
import { http } from '@/utils'

function delay(ms = 200) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

/* 登录 获取 accessToken */
export const loginApi: any = async (data) => {
  const res: any = await http.post('/api/login', {
    data,
  })
  const resData = res.data
  const store = useUserStore()
  store.setUserInfo({
    refreshToken: resData.refreshToken,
    accessToken: resData.accessToken,
  })
}

/* 拿 refreshToken 换取 accessToken 与 新 refreshToken */
/* 即刷新 accessToken */
export const refreshTokenApi: any = () => {
  // 这里如果原来就有请求的就直接返回，
  const store = useUserStore()
  const { refreshToken } = store.userInfo || {}
  return http
    .get<{ refreshToken: string, accessToken: string }>('/api/refresh', {
      data: {
        refreshToken,
      },
      headers: {
        _isRefreshToken: true,
      },
    })
    .then(
      (res) => {
        store.setUserInfo({
          refreshToken: res.data.refreshToken,
          accessToken: res.data.accessToken,
        })
        return [res, null]
      },
      e => [null, e],
    )
}

/* 获取用户信息 */
export const getUserInfoApi: any = async () => {
  http.setup({
    redirectToLogin: true,
  })
  return http.get('/api/userInfo', { debug: true, debugFormat: 'json', hideErrorToast: false })
}

export function isRefreshRequest(config: any) {
  return !!config.__isRefreshToken
}
